package com.wu.flandre.api.page;

import com.wu.flandre.component.GlobalConstant;
import com.wu.flandre.util.CommonUtil;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * WeChatAuthLoginApi <br/>
 *
 * @author 50816 <br/>
 * @date 2019/12/1 20:19 <br/>
 */
@Controller
@Slf4j
@Api(value = "H5界面微信oauth登录")
public class WeChatAuthLoginApi {

    @Value("${wechat.appid}")
    String appId;
    @Value("${wechat.appsecret}")
    String appSecret;
    @Autowired
    CommonUtil commonUtil;
    @Autowired
    RestTemplate restTemplate;

    @GetMapping("/code")
    public ModelAndView requestAccessCode() {
        Map<String, String> params = new HashMap<>();
        params.put("appId", appId);
        try {
            params.put("redURL", URLEncoder.encode("http://i2r9gy.natappfree.cc/getAuthToken", "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            log.error("URL encode异常" + e.getMessage());
        }
        params.put("scope", GlobalConstant.H5_OAUTH_SCOPE_INFO);
        String url = commonUtil.stringReplaceByMap(GlobalConstant.GET_CODE_URL, params);
        return new ModelAndView(new RedirectView(url));
    }

    @GetMapping("/getAuthToken")
    @ResponseBody
    public String getAccessCode(String code, String state) {
        Map<String, String> params = new HashMap<>();
        params.put("appId", appId);
        params.put("secret", appSecret);
        params.put("code", code);
        String url = commonUtil.stringReplaceByMap(GlobalConstant.CODE_TO_ACCESSTOKEN_URL, params);
        String forObject = restTemplate.getForObject(url, String.class);
        System.out.println(forObject);
        return forObject;
    }
}
